/* 
 * Update calendar entry
 */

// Create the calendar service object
var calendarService = new
google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');

// The default "owncalendars" feed is used to update existing calendar 
// entry from the authenticated user
var feedUri = 'http://www.google.com/calendar/feeds/default/owncalendars/full';

// This callback method that will be called when getOwnCalendarsFeed() returns feed data
var callback = function(result) {
  
  // Obtain the array of CalendarEntry
  var entries = result.feed.entry;

  // Use this string to identify targeted calendar entry for update
  var targetTitleStart = 'JS-Client';

  // Flag to indicate whether a match is found
  var calendarFound = false;

  // The first matched calendar entry will have its title updated to this string
  var newTitle = 'JS-Client: update calendar';
  
  for (var i = 0; i < entries.length; i++) {
    var calendarEntry = entries[i];
    var calendarTitle = calendarEntry.getTitle().getText();

    // The first matched is located!
    if (calendarTitle.substring(targetTitleStart.length, 0) == targetTitleStart) {      
      calendarFound = true;

      // Update the calendar's title
      calendarEntry.setTitle(google.gdata.Text.create(newTitle));
      calendarEntry.updateEntry(
          function() {
            PRINT('calendar updated!');
          }, 
          handleError
      );      
      break;
    }
  }
  
  // If no matched calendar is found, print this message
  if (!calendarFound) {
    PRINT('Cannot find calendar with title starts with: ' + targetTitleStart);
  }
}

// Error handler to be invoked when getOwnCalendarsFeed() or updateEntry() 
// produces an error
var handleError = function(error) {
  PRINT(error);
}

// Submit the request using the calendar service object
calendarService.getOwnCalendarsFeed(feedUri, callback, handleError);
